const qiniu = require('qiniu');

const config = new qiniu.conf.Config();
// 空间对应的机房
// config.zone = qiniu.zone.Zone_z0;
// 是否使用https域名
//config.useHttpsDomain = true;
// 上传是否使用cdn加速
config.useCdnDomain = true;

//需要填写你的 Access Key 和 Secret Key
const accessKey = 'oKjJCHepg17nTZUx3XUu6aELf5jPgSDBNmQj5K7x';
const secretKey = 'sBfa_iyJa72ca3VAbxcgVTtX1NULN7bXRKPfbyvx';
const mac = new qiniu.auth.digest.Mac(accessKey, secretKey);

//要上传的空间
const bucket = 'zhongzheng';

//构建上传策略函数
const uptoken = (bucket, key) => {
  const putPolicy = new qiniu.rs.PutPolicy({
    scope: bucket + ":" + key,
    callbackBody: '{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}',
    callbackBodyType: 'application/json',
  });
  return putPolicy.uploadToken(mac);
};

const formUploader = new qiniu.form_up.FormUploader(config);
const putExtra = new qiniu.form_up.PutExtra();

//构造上传函数
const uploadFile = (filename, localFile) => {

  const token = uptoken(bucket, filename);

  return new Promise((resolve, reject) => {
    formUploader.putFile(token, filename, localFile, putExtra, function (respErr, respBody, respInfo) {
      if (respErr) {
        reject(respErr);
        throw respErr;
      }
      if (respInfo.statusCode == 200) {
        resolve(respBody);
      } else {
        console.log(respInfo.statusCode);
        reject(respInfo);
      }
    });
  });
};

module.exports = uploadFile;
